package com.example.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.entry.Notice;
import com.example.service.INoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*
 * 公告后台管理控制器
 * */
@RequestMapping("/admin/notice")
@RestController
public class NoticeController {

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*
    * 根据id查询信息
    * */
    @GetMapping("/notice-info/={id}")
    public Result getNoticeOne(@PathVariable Integer id){
        Notice byId = noticeService.getById(id);
        return Result.success(byId);
    }

    /*
     * 根据id进行删除
     * */
    @GetMapping("/delete/id={id}")
    public Result deleteNoticeInfo(@PathVariable Integer id) {
        noticeService.removeById(id);
        return Result.success("删除成功");
    }

    @PostMapping("/batchd_delete")
    public Result batchDelete(@RequestBody List<Integer> ids){
        noticeService.removeBatchByIds(ids);
        return Result.success("删除成功");
    }

    /*
     * 修改或保存信息
     * */
    @PostMapping("/update")
    public Result updateOrSavNotice(@RequestBody Notice notice){
//        QueryWrapper<Notice> wrapper = new QueryWrapper<>();
//        wrapper.eq("is_release", notice.getIsRelease());
//        Notice one = noticeService.getOne(wrapper);

        noticeService.saveOrUpdate(notice);
        return Result.success("更新成功");
    }

    /*
     * 分页查询
     * */
    @GetMapping("/page")
    public Result getPageNotice(@RequestParam Integer pageNum,
                              @RequestParam Integer pageSize,
                              @RequestParam(defaultValue = "") String title,
                              @RequestParam(defaultValue = "") String createUserName){
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        // 根据is_release进行升序排序
        queryWrapper.orderByAsc("is_release");
        // 根据条件进行模糊查询
        if(!"".equals(title)){
            queryWrapper.like("title", title);
        }
        if(!"".equals(createUserName)){
            queryWrapper.like("create_user_name", createUserName);
        }
        // 分页构造器
        Page<Notice> page = noticeService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }
}
